use std::collections::HashMap;
use url::{Url};
use warp::{Filter};
use serde::{Serialize, Deserialize};
use std::convert::Infallible;
use std::hash::Hash;
use std::str::FromStr;
use std::time::Duration;
use rquest::{cookie, Method};
use rquest::header::{HeaderMap, HeaderName, HeaderValue};
use rquest::Impersonate;



#[derive(Serialize, Deserialize)]
struct Resp {
    text: String,
    code: i16,
    status_code: i16,
    message: String,
    cookies: std::collections::HashMap<String, String>,
    headers: std::collections::HashMap<String, Vec<String>>,

}

#[derive(Serialize, Deserialize, Debug)]
struct ForwardItem {
    proxy: String,
    method: String,
    headers: std::collections::HashMap<String, String>,
    url: String,
    data: String,
}

async fn handle_forward(item: ForwardItem) -> Result<impl warp::Reply, Infallible> {
    // 这里可以处理接收到的 ForwardItem 数据
    // 例如，打印出来或进行其他操作
    println!("{:#?}", item.headers);

    let proxystr = format!("{}", &item.proxy);

    let proxy = rquest::Proxy::all(proxystr).unwrap();
    let cookie = cookie::Jar::default();
    let uri = Url::parse(&*item.url).unwrap();
    let client = rquest::Client::builder()
        .proxy(proxy)
        .impersonate(Impersonate::Firefox135)
        .brotli(true)
        .permute_extensions(true)
        .timeout(Duration::from_secs(10))
        .connection_verbose(true)
        .danger_accept_invalid_certs(true)
        .cookie_provider(cookie.into())
        .build().unwrap();
    // 从响应头中获取 cookies
    // println!("get cookie {:#?}", item.headers.get("cookie").is_none());
    if !item.headers.get("cookie").is_none(){
        let a: Vec<_> = item.headers.get("cookie").unwrap().split("; ").into_iter().map(|x| {
            return x.parse::<HeaderValue>().unwrap()
        }).collect();
        client.set_cookies(&uri,a );
    }


    let body = format!("{}", &item.data);
    let mut header_map = HeaderMap::new();
    for (key, value) in &item.headers {
        if let (Ok(name), Ok(val)) = (HeaderName::from_bytes(key.as_bytes()), HeaderValue::from_str(value)) {
            header_map.insert(name, val);
        }
    }

    let req = client.request(Method::from_str(&item.method).unwrap(), &item.url)
        .body(body)
        .headers(header_map)

        .build().unwrap();
    let mut response = client.execute(req).await.unwrap();
    let respCk = response.cookies();
    let mut respCookies: HashMap<_, _> = respCk.map(|x|
        (x.name().to_string(), x.value().to_string())
    ).collect();
    let headers = response.headers();
    let mut headerss: HashMap<String, Vec<_>> = HashMap::default();
    let headersKey = headers.keys();
    headersKey.into_iter().for_each(|key|{
        let vv = headers.get_all(key);
        // println!("{:#?} {:#?}", key, vv.to_str().unwrap());

        let vv2: Vec<String> = vv.iter().map(|x|{
            return x.to_str().unwrap().to_string();
        }).collect();
        headerss.insert(key.to_string(), vv2);
    });

    let text = response.text().await.unwrap();

    let rrr = Resp {
        text: text.clone(),
        code: 0,
        status_code: 200,
        message: text,
        cookies: respCookies,
        headers: headerss,
    };
    Ok(warp::reply::json(&rrr))
    // 从列表中随机选择一个元素
    // if let Some(random_item) =  {
    //     println!("Random item: {}", random_item);
    // } else {
    //     println!("List is empty");
    // }/



    //

    //
    //     // Use the API you're already familiar with
    // let resp = client.get("https://tls.peet.ws/api/all")


    // 返回一个成功的响应
}

#[tokio::main]
async fn main() {
    // 定义路由
    let forward_route = warp::post()
        .and(warp::path("tls"))
        .and(warp::path("forward"))
        .and(warp::path::end())
        .and(warp::body::json())
        .and_then(handle_forward);
    // 启动服务器
    warp::serve(forward_route)
        .run(([0, 0, 0, 0], 58000))
        .await;
}





// #[tokio::main]
// async fn main() {

//     let proxystr = format!("{}", "127.0.0.1:7890");

//     let proxy = rquest::Proxy::all(proxystr);
//     match proxy {
//         Ok(pro) => {
//             let client = rquest::Client::builder()
//                 .proxy(pro)
//                 .impersonate(Impersonate::Chrome130)
//                 .timeout(Duration::from_secs(10))
//                 .redirect(redirect::Policy::limited(10))
//                 .build();
//             match client {
//                 Ok(cli) => {
//                     // let mut headerMap = HeaderMap::new();
//                     // for (key, value) in &item.headers {
//                     //     headerMap.insert(HeaderName::from_str(key), value.parse().unwrap());
//                     // }
//                     // headerMap.insert("a", "earth".parse().unwrap());

//                     let request = cli.get("https://booking.jetstar.com/au/en/booking/search-flights?Currency=AUD&adults=1&children=0&infants=0&origin1=ADL&destination1=BNE&departuredate1=2024-12-17")
//                         .header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
//                         .header("accept-language", "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6")
//                         .header("cache-control", "no-cache")
//                         .header("pragma", "no-cache")
//                         .header("priority", "u=0, i")
//                         .header("referer", "https://www.jetstar.com/")
//                         .header("sec-ch-ua-mobile", "?0")
//                         .header("sec-fetch-dest", "document")
//                         .header("sec-fetch-mode", "navigate")
//                         .header("sec-fetch-site", "same-site")
//                         .header("sec-fetch-user", "?1")
//                         .header("upgrade-insecure-requests", "1")
//                         .header("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
//                         .header("cookie", "_abck=7C0DD8DB209AE5F6DD06C7570607427B~-1~YAAQBetGaLLS3h+TAQAAxujATAyT+vv8QIwsfNKJfTd3/TJwDFjxtSPusC20fYw7OJSt8xXItsyW+xYIlu3SE9bdE2nuim9aGVK36OVlw0CCuq2FULBJHAWzrvbbj66QaIaFfdhJeyWRUZTkS3ykNCzOzIauSJUnHOEyKX+GdubmKaLUYBtr1nR37glfceFCeTUHtJWuWTMyWpQwjuN9qh7tLw0/6fccF/CAFc6piojXE//W1D5I/9vua7FlBlStsf4RENY1+oG/RhfiXvDXYUgmX5P6xWUj5gDeINO/P0KF9jyu1RYZt4N0F5d8XQ7Xh8Yd4v6KzJUCffuhYLN6NvveM/Y0AGQ9ygytMDQcay4kZwjbOA6SH7rs5oJ7HHPfcV9iukGkTHQQxUKRJ5Aa/Z1xQnlArCpAhm/EoCYO~-1~-1~-1; bm_sz=8D9194332C1222C159EB293D1EEFCD88~YAAQBetGaMbS3h+TAQAAP+vATBmmHOy8qgWxLHf94s6q3QqL/7f+j2QZ1dtZDdf26qLsduJMNQWVlN7HKl7uzX1sL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TFMqTx7ongMamdTazISNYtdwuUjAI69vjaGrXCS1YRimy85tZdXo; bm_sc=2~1~279964273~YAAQBetGaMrS3h+TAQAAZOzATAJZ1JrBBVxvKBPDNETwfDEcmBcw4uI7Qr9m4rSvI4AwDgtVm3UbOt/KS6DDH3azAsNGLHraVHF27cSo7oa8adS93PfijbX8oXNCbPtOLKgcxSivdFE/eamo6E36V1IiHASYd2zoJYD2pUXKzLQFYfXV0ivbWjuGK9O0gSkaZSBAmakb0DMlBtQxwe5lzP3FCjKAbfathGMa/4ukXBp0AvgmdMVNrixGRpnWuOgA3kfQJ+0u4W6bMh43IhkB03sGtHOqE6R2U1pUzE4VODn8WuVChef8AlOBXWHTtyGY5MztAsYW6HVn99agiVBx239eu1Yk8qKQjmwZRM9Nfto4euKwCeNGm19C9PshCHo0y/K3f+YIlETeF3EdGzxdXFtCGNQgTrK4j9nXsLT4mHAFMlZSmMkpOMJX7g0X28ls+A==; bm_so=C3D42BC365960E0ED64D70553265E20E79BA2D6EC49DD0EACE82E3D549B03B0F~YAAQBetGaMXS3h+TAQAAP+vATAHjWrwet0i+5isS3IrEP690i8UbvvLMYeZrqppZRlLUhZzhdv1wrvSTTLynD0fCPWn4aLP1KlKGqHZZa8ygBOCULm0DYUWA/OkjvFPRRNmrnvy/dL0mEi2Zn5IUwuE5FivScSXBmo+sP6w5AF07VcqAEUT3bMjcD4Zh+IExibHgeRs2mMlQdtAOC55txEBTnSUyPUfURq/v56XiYbLOxcSZcfKBymFp+ZGWrNTyoN5UH3BRLkBo8JJQFL2MEmzq6MUtcMK7/WcJNd822Pxxz3TxcAww9cMo3Ott86slkgit34UKlVA5Hdw10zexnAUPTIQyWw03C9PNJBoimIJUhBnok4Owvo89vYgr3KiL2A9uh1d/I4p5U0y3hT8h6DQnkQNuwcze3x29pLW5Kf187VikTMrfUm6pe90H7QFAdzZWGgquWSGIQD+d5MQ=")
//                         // .header("sec-ch-ua", "\"Chromium\";v=\"121\", \"Not)A;Brand\";v=\"24\", \"Microsoft Edge\";v=\"121\"")
//                         // .header("sec-ch-ua-mobile", "?0")
//                         // .header("sec-ch-ua-platform", "\"macOS\"")
//                         .build();
//                     match request {
//                         Ok(req) => {
//                             let response = cli.execute(req).await;
//                             match response {
//                                 Ok(resp) => {
//                                     let text = resp.text().await;
//                                     match text {
//                                         Ok(te) => {
//                                             println!("{}", te);
//                                         }
//                                         Err(e2) => {
//                                         }
//                                     }
//                                 }
//                                 Err(e1) => {
//                                     print!("{}", e1);
//                                 }
//                             }
//                         }
//                         Err(e3) => {
//                         }
//                     }

//                 }
//                 Err(err) => {
//                 }
//             }
//         }
//         Err(e2) => {
//         }
//     }
// }